//
//  XHFirstViewController.m
//  elxc
//
//  Created by fengyn on 16/3/14.
//  Copyright © 2016年 lexingsoft. All rights reserved.
//

#import "XHFirstViewController.h"

#import "YNCycleScrollView.h"
#import "XHAVPlayerCell.h"

#import "Services.h"
#import "AxcRedEnvelopeView.h"

#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import <UIAlertView+Blocks.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "HMSegmentedControl.h"
#import "UINavigationController+YNBase.h"
#import <DateTools/DateTools.h>
#import <AddressBookUI/AddressBookUI.h>
#import <ContactsUI/ContactsUI.h>

#define kTextFieldTagMobile 1988
#define NAVBAR_CHANGE_POINT 0


@interface XHFirstViewController ()<XHAVPlayerCellDelegate,UIWebViewDelegate,AxcRedEnvelopeViewDelegate,AxcRedEnvelopeViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *ui_tableView;
@property (strong, nonatomic) NSArray * urlArray;
@property (strong, nonatomic) NSOperation *operation;
@property (strong, nonatomic) NSString *localFilePath;
@property (strong, nonatomic) NSTimer *timer;
@property (strong, nonatomic) CALayer *layer;

@property (strong, nonatomic) NSMutableArray *imageArray;
@property (strong, nonatomic) AxcRedEnvelopeView *redView;

@end

@implementation XHFirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.urlArray = [NSArray new];
    self.urlArray = @[@"http://cn-tj8-cu.acgvideo.com/vg7/1/1c/11493712-1.mp4?expires=1481739900&ssig=Lpx0TV_m-dAgWL04k24aqw&oi=2086159136&nfa=jh1gYOK5yu5onKTDA7JgFw==&dynamic=1"];
    [PublicMethod setExtraCellLineHidden:self.ui_tableView];
    [self.ui_tableView registerNib:[UINib nibWithNibName:@"XHAVPlayerCell" bundle:nil] forCellReuseIdentifier:XHAVPlayerCellIdentifier];
    
    self.redView=[[AxcRedEnvelopeView alloc]initWithFrame:self.view.frame];
    [self.redView setTransform:CGAffineTransformMakeRotation(M_PI_4)];
    self.redView.delegate = self;
    self.redView.dataSource=self;
    self.redView.AxcRedEnvelope_Size = CGSizeMake(50, 50);
    [self.view addSubview:self.redView];
    [self.redView starPerformance];
}

- (AxcRedEnvelope *)AxcRedEnvelope:(AxcRedEnvelope *)redEnvelope createAtIndex:(NSInteger)index{
    if (!redEnvelope) {
        redEnvelope = [[AxcRedEnvelope alloc] init];
        redEnvelope.backgroundColor = [UIColor greenColor];
        [redEnvelope setImage:[UIImage imageNamed:@"red"] forState:UIControlStateNormal];
    }
    return redEnvelope;
}

// 点击事件的代理回调
-(void)AxcRedEnvelope:(AxcRedEnvelope *)redEnvelope didSelectAtIndex:(NSInteger)index{
    NSLog(@"%ld",index);
    
    [UIView animateWithDuration:0.3
                     animations:^{
                         redEnvelope.alpha = 0;
                     }completion:^(BOOL finished) {
                         [redEnvelope removeFromSuperview];
                     }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.ui_tableView reloadData];
//    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(addLayer:) userInfo:nil repeats:YES];
}


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSUInteger rows=self.urlArray.count;
    return rows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XHAVPlayerCell * cell = [self.ui_tableView dequeueReusableCellWithIdentifier:XHAVPlayerCellIdentifier];
    cell.delegate=self;
    if([ServiceManager fileExistsAtPath:self.localFilePath])
    {
        cell.ui_title.text = @"熊猫tv（已下载）";
//        cell.ui_title.font=[UIFont fontWithName:@"PingFangSC-Medium" size:18];
        cell.ui_MB.hidden=YES;
        cell.ui_progressView.hidden=YES;
        cell.ui_cancel.hidden=YES;
        [cell.ui setTintColor:[ColorManager colorWithHexString:@"#000000" alpha:0.5]];
    }
    else
    {
        cell.ui_title.text = @"熊猫tv（未下载）";
        cell.ui_MB.hidden=YES;
        cell.ui_progressView.hidden=YES;
        cell.ui_cancel.hidden=YES;
    }
    cell.ui_runButton.tag=indexPath.row;
    cell.ui.tag=indexPath.row;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height=250;
    return height;
}

#pragma mark - XHAVPlayerCellDegate

//播放
- (void)cell:(XHAVPlayerCell*)cell runAction:(id)sender


{
//    cell.testString = ^(NSString * testStr){
//        
//        NSLog(@"%@",testStr);
//    };
//    if([ServiceManager fileExistsAtPath:self.localFilePath])
//   {
//        NSURL *url = [NSURL fileURLWithPath:self.localFilePath];
//        AVPlayerViewController *viewController = [[AVPlayerViewController alloc]init];
//        viewController.player=[[AVPlayer alloc]initWithURL:url];
//        [viewController.player play];
//        NSLog(@"本地播放");
//        [self presentViewController:viewController animated:YES completion:nil];
//    }
//    else
//    {
//        NSString * urlSrting=self.urlArray[cell.ui_runButton.tag];
//        NSURL *url = [NSURL URLWithString:urlSrting];
//        AVPlayerViewController *player = [[AVPlayerViewController alloc]init];
//        player.player = [[AVPlayer alloc]initWithURL:url];
//        [player.player play];
//        NSLog(@"网络播放");
//        [self presentViewController:player animated:YES completion:nil];
//    }
    
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
//    NSDictionary *parameters = @{@"telephone":@"15929922717"};
//    [manager POST:@"http://192.168.1.104:8080/api/userInfo/getIdentify.do"parameters:parameters
//          success:^(AFHTTPRequestOperation *operation,id responseObject) {
//              NSLog(@"Success: %@", responseObject);
//          }failure:^(AFHTTPRequestOperation *operation,NSError *error) {
//              NSLog(@"Error: %@", error);
//          }];
    
    
    
    NSString  *qqNumber=@"792370351";
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]) {
        UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
        NSURL * url=[NSURL URLWithString:[NSString stringWithFormat:@"mqq://im/chat?chat_type=wpa&uin=%@&version=1&src_type=web",qqNumber]];
        
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        webView.delegate = self;
        [webView loadRequest:request];
        [self.view addSubview:webView];
    }else{
    }
}

//下载
- (void)cell:(XHAVPlayerCell*)cell downAction:(id)sender
{
    cell.ui_progressView.progress=0;
    cell.ui_progressView.hidden=NO;
    NSString * urlSrting=self.urlArray[cell.ui.tag];
    self.operation = [ServiceManager downloadFileWithUrl:urlSrting downloadSuccess:^(NSString *localFilePath) {
        if ([ServiceManager fileExistsAtPath:self.localFilePath]) {
            NSLog(@"%@",self.localFilePath);
            [PromptAction showInfoPrompt:@"下载完成"];
            cell.ui_MB.hidden=YES;
            cell.ui_progressView.hidden=YES;
            cell.ui_cancel.hidden=YES;
            NSUserDefaults * userDefaluts = [NSUserDefaults standardUserDefaults];
            [userDefaluts setObject:self.localFilePath forKey:@"path"];
            [self.ui_tableView reloadData];
        }else{
            [PromptAction showInfoPrompt:@"下载开始之前"];
            cell.ui_MB.hidden=YES;
            cell.ui_progressView.hidden=YES;
            cell.ui_cancel.hidden=YES;
        }
        
    } downloadFailure:^(NSError *error) {
        [ServiceManager removeFileWithPath:self.localFilePath];
        if (error.code!=NSURLErrorCancelled) {
            [PromptAction showErrorPrompt:@"数据错误"];
            cell.ui_MB.hidden=YES;
            cell.ui_progressView.hidden=YES;
            cell.ui_cancel.hidden=YES;
        }
    } progress:^(float progress, NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        cell.ui_MB.hidden=NO;
        cell.ui_progressView.hidden=NO;
        cell.ui_cancel.hidden=NO;
        cell.ui_progressView.progress=progress;
        cell.ui_MB.text = [NSString stringWithFormat:@"已下载%.2f...(%@/%@)",progress,[YNFileMethod convertSize:totalBytesRead],[YNFileMethod convertSize:totalBytesExpectedToRead]];
    }];
}

//取消
- (void)cell:(XHAVPlayerCell *)cell cancelAction:(id)sender
{
    cell.ui_progressView.hidden = YES;
    cell.ui_MB.hidden=YES;
    cell.ui_cancel.hidden=YES;
    [self.operation cancel];
}

//获取本地地址
- (NSString *)localFilePath{
    if (!_localFilePath)
    {
        if (![NSString checkNullString:self.urlArray[0]])
        {
            _localFilePath=[ServiceManager getLocationFilePathWithUrl:self.urlArray[0]];
            NSUserDefaults * userDefaluts = [NSUserDefaults standardUserDefaults];
            [userDefaluts setObject:self.localFilePath forKey:@"path"];
        }
    }
    return _localFilePath;
}

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    CGFloat offsetToShow = 200.0;//滑动多少就完全显示
//    CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow;
//    [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = alpha;
//}

@end
